import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { usePermissionStore } from '@/stores/permission'

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { title: '登录', requiresAuth: false }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/Register.vue'),
    meta: { title: '注册', requiresAuth: false }
  },
  {
    path: '/',
    name: 'Layout',
    component: () => import('@/layout/index.vue'),
    meta: { title: '首页', requiresAuth: true },
    children: [
      {
        path: '',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard.vue'),
        meta: { title: '仪表盘', requiresAuth: true }
      },
      {
        path: '/users',
        name: 'User',
        component: () => import('@/views/user/index.vue'),
        meta: { title: '用户管理', requiresAuth: true, permission: 'user:manage' }
      },
      {
        path: '/roles',
        name: 'Role',
        component: () => import('@/views/role/index.vue'),
        meta: { title: '角色管理', requiresAuth: true, permission: 'role:manage' }
      },
      {
        path: '/permissions',
        name: 'Permission',
        component: () => import('@/views/permission/index.vue'),
        meta: { title: '权限管理', requiresAuth: true, permission: 'permission:manage' }
      },
      {
        path: '/menus',
        name: 'Menu',
        component: () => import('@/views/menu/index.vue'),
        meta: { title: '菜单管理', requiresAuth: true, permission: 'menu:manage' }
      },
      {
        path: '/regulation-services',
        name: 'RegulationServices',
        component: () => import('@/views/regulation-services/index.vue'),
        meta: { title: '调节服务数据管理', requiresAuth: true, permission: 'regulation_service:manage' }
      },
      {
        path: '/gep-parameters',
        name: 'GepParameters',
        component: () => import('@/views/gep-parameters/index.vue'),
        meta: { title: 'GEP参数管理', requiresAuth: true, permission: 'gep_parameter:manage' }
      },
      {
        path: '/gep-results',
        name: 'GepResults',
        component: () => import('@/views/gep-results/index.vue'),
        meta: { title: 'GEP结果管理', requiresAuth: true, permission: 'gep_result:manage' }
      },
      {
        path: '/vep-parameters',
        name: 'VepParameters',
        component: () => import('@/views/vep-parameters/index.vue'),
        meta: { title: 'VEP参数管理', requiresAuth: true, permission: 'vep_parameter:manage' }
      },
      {
        path: '/vep-results',
        name: 'VepResults',
        component: () => import('@/views/vep-results/index.vue'),
        meta: { title: 'VEP结果管理', requiresAuth: true, permission: 'vep_result:manage' }
      },
      {
        path: '/profile',
        name: 'Profile',
        component: () => import('@/views/Profile.vue'),
        meta: { title: '个人资料', requiresAuth: true }
      }
    ]
  },
  {
    path: '/403',
    name: 'Forbidden',
    component: () => import('@/views/403.vue'),
    meta: { title: '访问被拒绝', requiresAuth: false }
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/404.vue'),
    meta: { title: '页面不存在', requiresAuth: false }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore()
  const permissionStore = usePermissionStore()
  
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 生态数据管理系统` : '生态数据管理系统'
  
  // 不需要认证的页面直接通过
  if (!to.meta.requiresAuth) {
    next()
    return
  }
  
  // 检查是否已登录
  if (!userStore.token) {
    next('/login')
    return
  }
  
  // 检查用户信息是否已加载
  if (!userStore.userInfo) {
    try {
      await userStore.getUserInfo()
      await permissionStore.getUserPermissions()
      await permissionStore.getUserMenus()
    } catch (error) {
      userStore.logout()
      next('/login')
      return
    }
  }
  
  // 检查权限
  if (to.meta.permission) {
    const hasPermission = permissionStore.hasPermission(to.meta.permission)
    // 临时允许admin用户访问所有页面
    const userStore = useUserStore()
    const isAdmin = userStore.userInfo && userStore.userInfo.username === 'admin'
    if (!hasPermission && !isAdmin) {
      next('/403')
      return
    }
  }
  
  next()
})

export default router 